﻿using SimpleEncryption.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleEncryption.CryptoSteps
{
    /// <summary>
    /// The scrambled positions algorithm basically shifts characters forward
    /// </summary>
    public class ScramblePositions : ICryptoStep
    {
        /// <summary>
        /// The scrambled relations
        /// </summary>
        public Dictionary<int, int> ScrambledRelations = new Dictionary<int, int>();


        public ScramblePositions()
        {
            ScrambledRelations = new Dictionary<int, int>();
        }
        /// <summary>
        /// Encrypts the specified text with an fixed algorithm
        /// </summary>
        /// <param name="text">The text to encrypt</param>
        /// <returns>
        /// The encrypted text
        /// </returns>
        public string Encrypt(string text, string password)
        {
            var encryptedCharArray = text.ToCharArray().ToList();
            foreach (var scrambledRelation in ScrambledRelations)
            {
                var startPosition = Math.Abs(scrambledRelation.Key);

                int newPosition = Math.Abs(scrambledRelation.Value);

                startPosition =startPosition % text.Length ;
             
                newPosition = newPosition % text.Length;
             
                char valueToMove = encryptedCharArray[startPosition];
          
                encryptedCharArray.RemoveAt(startPosition);
                encryptedCharArray.Insert(newPosition, valueToMove);

                encryptedCharArray[newPosition] = valueToMove;
            }
            return new string(encryptedCharArray.ToArray());
        }

        /// <summary>
        /// Decrypts the specified text with an fixed algortihm
        /// </summary>
        /// <param name="text">The text to decrypt</param>
        /// <returns>
        /// the decrypted text
        /// </returns>
        public string Decrypt(string text, string password)
        {
            var encryptedCharArray = text.ToCharArray().ToList();
            var test = ScrambledRelations.ToList();
            test.Reverse();
            foreach (var scrambledRelation in test)
            {
                var startPosition = Math.Abs(scrambledRelation.Value);

                int newPosition =  Math.Abs(scrambledRelation.Key);
                startPosition = startPosition % text.Length;

                newPosition = (newPosition) % text.Length;

               
                char valueToMove = encryptedCharArray[startPosition];
                encryptedCharArray.RemoveAt(startPosition);
                encryptedCharArray.Insert(newPosition, valueToMove);

                encryptedCharArray[newPosition] = valueToMove;
            }
            return new string(encryptedCharArray.ToArray());
        }
    }
}
